# -*- coding: utf-8 -*-
import re

from PIL import Image
import os

from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.video.VideoClip import ImageClip, TextClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
from moviepy.video.compositing.concatenate import concatenate_videoclips
from moviepy.config import change_settings
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip

change_settings({"IMAGEMAGICK_BINARY": r"C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe"})

def resize_images(image_files, desired_size):
    resized_images = []
    for image_file in image_files:
        # 打开一张图片文件
        with Image.open(image_file) as img:
            # 调整图片大小到目标尺寸
            img = img.resize(desired_size, Image.ANTIALIAS)
            # 将调整后的图片保存到临时文件
            temp_file = f"temp_{os.path.basename(image_file)}"
            img.save(temp_file)
            resized_images.append(temp_file)
    return resized_images


def create_video_from_images(image_files, subtiles_materials, audio_file, output_file, fps=24, desired_size=(1024, 1024)):
    # 处理字幕
    total_duration = 0
    sub_duration = []
    start_time = 0
    subtiles = []
    # 遍历字幕列表
    for subtiles_material in subtiles_materials:
        duration = subtiles_material['duration']
        if duration is None:
            continue

        # 创建字幕剪辑
        subtile = (TextClip(subtiles_material['subtile'], fontsize=40, font='SimHei', size=(1024, 80), align='center',
                            color='white')
                   .set_position(('center', 'bottom')).set_duration(duration).set_start(start_time))
        subtiles.append(subtile)

        # 更新起始时间
        start_time += duration
        total_duration += duration

    img_no = 0
    while img_no < len(image_files):
        sub_duration.append(total_duration / len(image_files))
        img_no += 1

    # 将图片调整到目标尺寸
    # resized_images = resize_images(image_files, desired_size)

    # 加载音频文件
    audio = AudioFileClip(audio_file)

    # 设置图片展示时长为2秒
    image_duration = 5

    # 创建单独的图片剪辑并设置展示时长
    # clips = []
    # index = 0
    # for img in image_files:
    #     clips.append(ImageClip(img).set_duration(sub_duration[index]).set_fps(fps))
    #     index = index + 1
    background_image = ImageSequenceClip(image_files, durations=sub_duration)

    # 将所有图片剪辑拼接成循环播放的一个视频剪辑
    # video_clip = concatenate_videoclips(clips, *txts, method="compose")

    # 给视频剪辑设置音频
    # final_video = video_clip.set_audio(audio)
    final_video = CompositeVideoClip([background_image.set_duration(total_duration), *subtiles]).set_audio(audio)

    # 将结果写入输出文件
    final_video.write_videofile(output_file, codec="libx264", audio_codec="aac", fps=fps)

    # 清理临时文件
    # for temp_file in resized_images:
    #     os.remove(temp_file)

speed = 5
def format_txt(txt_list_f):
    merged_string = ''.join(txt_list_f)
    merged_string = merged_string.replace("\n", "").replace("\r", "")
    total_duration = len(merged_string) / speed
    subtitles_list = re.split(r'[。，]', merged_string)
    # subtitles_list = merged_string.split("。")
    subtitles_list.pop()
    sub_duration = []
    for txt in txt_list_f:
        duration = len(txt) / speed
        sub_duration.append(duration)
    return {"total_duration": total_duration,
            "subtitles_list": subtitles_list,
            "sub_duration": sub_duration
            }
